import React, { useEffect } from 'react';
import { useTRState, TjChart } from '@/pages/ETrade/components';
import { COLORS, TIME_24 } from '@/pages/ETrade/components/helper';
import { PageLoading } from '@/components/index.js';
import { TRDefault } from '@/components/index.js';
import { getGraphicsAnalyse } from './services';
import { getCssVariableValue } from '@/utils/utils';

import styles from './index.less';

export default ({ params }) => {
  const [state, setState] = useTRState({
    loading: false,
    chartTotal: null,
    chartDetail: null,
  });

  // 请求数据（没有查询按钮，根据条件变化查询）
  useEffect(() => {
    fetch();
  }, [JSON.stringify(params)]);

  const fetch = async () => {
    if (!params) return;
    const { provinceId, stationIdList, startDate, endDate, contractIdList } = params;
    setState({ loading: true });
    const res = await getGraphicsAnalyse({
      provinceId,
      stationIdList,
      startDate,
      endDate,
      contractIdList,
    });
    const chartTotal = getChartTotal(res?.contractTotalAmount);
    const chartDetail = getChartDetail(res?.pointData);
    setState({
      chartTotal,
      chartDetail,
      loading: false,
    });
  };

  // 图配置
  const getChartTotal = (_data) => {
    if (!_data) return null;
    let xData = [];
    let listMap = {};
    for (const day in _data) {
      const list = _data[day] || [];
      const x = day.replace(/[-]/g, '');
      list.map(({ stationName, totalAmount }) => {
        if (!listMap[stationName]) {
          listMap[stationName] = {
            type: 'bar',
            name: stationName,
            props: { stack: 'A' },
            data: [],
          };
        }
        listMap[stationName].data.push(totalAmount);
      });
      xData.push(x);
    }
    const series = Object.values(listMap);
    return {
      series,
      color: COLORS,
      grid: { top: 24, left: 48, bottom: 48, right: 0 },
      tooltip: {
        enterable: true,
        extraCssText: 'max-height: 75%; overflow: hidden scroll;',
      },
      legend: {
        textStyle: {
          color: getCssVariableValue('--chart-legend-color'),
        },
      },
      xAxis: [
        {
          type: 'category',
          data: xData,
          axisLabel: {
            color: getCssVariableValue('--chart-font-color'),
          },
          axisLine: {
            lineStyle: {
              color: getCssVariableValue('--chart-x-line'),
            },
          },
          axisTick: {
            lineStyle: {
              color: getCssVariableValue('--chart-x-line'),
            },
          },
          axisPointer: {
            type: 'line',
            lineStyle: {
              color: getCssVariableValue('--chart-x-line'),
            },
          },
        },
      ],
      yAxis: [
        {
          type: 'value',
          name: 'MWh',
          nameTextStyle: {
            color: getCssVariableValue('--chart-font-color'),
          },
          axisLabel: {
            color: getCssVariableValue('--chart-font-color'),
          },
          axisLine: {
            lineStyle: {
              color: getCssVariableValue('--chart-y-line'),
            },
          },
          splitLine: {
            lineStyle: {
              color: getCssVariableValue('--chart-y-line'),
            },
          },
        },
      ],
    };
  };

  // 图配置
  const getChartDetail = (_data) => {
    if (!_data?.length) return null;
    let series1 = [];
    let series2 = [];
    _data.map(({ stationName, electric }) => {
      let name = stationName,
        data = electric;
      if (name.slice(-2) === '电量') {
        series1.push({
          name,
          data,
          type: 'line',
          props: {
            xAxisIndex: 0,
            yAxisIndex: 0,
          },
        });
      } else if (name.slice(-2) === '电价') {
        series2.push({
          name,
          data,
          type: 'line',
          props: {
            xAxisIndex: 1,
            yAxisIndex: 1,
          },
        });
      }
    });
    return {
      series: [...series1, ...series2],
      color: COLORS,
      grid: [
        { left: 48, right: 0, top: 24, height: '40%' },
        { left: 48, right: 0, bottom: 24, height: '40%' },
      ],
      axisPointer: {},
      legend: {
        textStyle: {
          color: getCssVariableValue('--chart-legend-color'),
        },
      },
      tooltip: {
        enterable: true,
        extraCssText: 'max-height: 75%; overflow: hidden scroll;',
      },
      xAxis: [
        {
          type: 'category',
          gridIndex: 0,
          data: TIME_24,
          axisLabel: {
            color: getCssVariableValue('--chart-font-color'),
          },
          axisLine: {
            lineStyle: {
              color: getCssVariableValue('--chart-x-line'),
            },
          },
          axisPointer: {
            type: 'line',
            lineStyle: {
              color: getCssVariableValue('--chart-x-line'),
            },
          },
        },
        {
          type: 'category',
          gridIndex: 1,
          data: TIME_24,
          axisLabel: { show: false },
          axisTick: { show: false },
          axisLine: {
            lineStyle: {
              color: getCssVariableValue('--chart-x-line'),
            },
          },
          axisPointer: {
            type: 'line',
            lineStyle: {
              color: getCssVariableValue('--chart-x-line'),
            },
          },
        },
      ],
      yAxis: [
        {
          type: 'value',
          name: 'MWh',
          gridIndex: 0,
          nameTextStyle: {
            color: getCssVariableValue('--chart-font-color'),
          },
          axisLabel: {
            color: getCssVariableValue('--chart-font-color'),
          },
          axisLine: {
            lineStyle: {
              color: getCssVariableValue('--chart-y-line'),
            },
          },
          splitLine: {
            lineStyle: {
              color: getCssVariableValue('--chart-y-line'),
            },
          },
        },
        {
          type: 'value',
          name: '元/MWh',
          gridIndex: 1,
          nameTextStyle: {
            color: getCssVariableValue('--chart-font-color'),
          },
          axisLabel: {
            color: getCssVariableValue('--chart-font-color'),
          },
          axisLine: {
            lineStyle: {
              color: getCssVariableValue('--chart-y-line'),
            },
          },
          splitLine: {
            lineStyle: {
              color: getCssVariableValue('--chart-y-line'),
            },
          },
        },
      ],
    };
  };

  /** renders */
  if (state.loading) return <PageLoading />;
  return (
    <div className={styles.charts}>
      <div className={styles.chart_title}>筛选日每日合约执行总量</div>
      <div className={styles.chart} style={{ flex: 1 }}>
        {!state.chartTotal ? <TRDefault type="emptysm" /> : <TjChart option={state.chartTotal} />}
      </div>
      <div style={{ height: 16 }} />
      <div className={styles.chart_title}>各场站每日24点电量/电价</div>
      <div className={styles.chart} style={{ flex: 2 }}>
        {!state.chartDetail ? <TRDefault type="emptysm" /> : <TjChart option={state.chartDetail} />}
      </div>
    </div>
  );
};
